/**
 * 
 */
package com.desksoft.ecommerce.helper.mall;

import static com.google.common.base.Preconditions.checkNotNull;

import java.text.MessageFormat;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.desksoft.ecommerce.entity.mall.dto.MallMessage;
import com.desksoft.ecommerce.service.interf.mall.IMallMessageService;
import com.desksoft.ecommerce.util.holder.ApplicationContextHolder;
import com.desksoft.ecommerce.util.result.ServiceResult;

/***************************************
 * <pre>
 * 版权所有：杭州迪科软件 保留所有权利
 * 创建日期: Apr 28, 2012
 * 创建作者：yejw
 * 文件名称：MallMsgHelper.java
 * 版本：1.0
 * 功能：
 * 最后修改时间：Apr 28, 2012
 * 修改记录：
 * </pre>
 *****************************************/
public class MallMsgHelper{

	protected final static Log log = LogFactory.getLog(MallMsgHelper.class);

	private static Map<Integer, List<MallMessage>> messages = null;

	static {
		messages = init();
		for(Integer key : init().keySet()){
			List<MallMessage> messList = messages.get(key);
			for (MallMessage mallMessage : messList) {
				mallMessage.setLastcontent(mallMessage.getContent());
			}
		}
	}

	private MallMsgHelper() {
	}

	private static Map<Integer, List<MallMessage>> init() {
		IMallMessageService mallMessageService = (IMallMessageService) ApplicationContextHolder
				.getBean("mallMessageService");
		checkNotNull(mallMessageService);

		ServiceResult<Map<Integer, List<MallMessage>>> servResult = mallMessageService
				.getMallMessages();
		
		if (!servResult.isSuccess()) {
			log.error("Failed to initialize the message resources!");
			return null;
		}

		return servResult.getResult();
	}

	/**
	 * 获取提示信息实体
	 * 
	 * @param siteID
	 * @param msgID
	 * @return
	 */
	public static MallMessage get(Integer siteID, final String msgID,
			Object... params) {
		if (messages == null || messages.isEmpty()) {
			init();
		}
	 	 List<MallMessage> sitemessage= messages.get(siteID);
       if(sitemessage == null || sitemessage.isEmpty()){
    	   init();
       }
		MallMessage m = null;
		for (Integer key : messages.keySet()) {
			if (key.longValue() == siteID.longValue()) {
				List<MallMessage> messList = messages.get(key);
				for (MallMessage mallMessage : messList) {
					if (mallMessage.getMsgid().equalsIgnoreCase(msgID)) {
						m = mallMessage;
						break;
					}
				}
			}

		}
		if (params != null && m != null) {
			String content = MessageFormat.format(m.getLastcontent(), params);
			m.setContent(content);
		}
		return m;
	}

	/**
	 * 根据信息ID取信息提示内容
	 * 
	 * @param messageCode
	 *            信息ID
	 * @param args
	 *            参数/参数数组
	 * @return
	 */
	public static String getMessage(Integer siteID, String messageCode,
			Object... args) {
		checkNotNull(messageCode);

		MallMessage message = get(siteID, messageCode, args);
		checkNotNull(message);

		return MessageFormat.format(message.getContent(), args);
	}
}
